<template>
    <a-row
        :gutter="8"
        :wrap="false">
        <a-col flex="auto">
            <a-card
                type="flex"
                title="用户管理">
                <x-toolbar class="mb-8-2">
                    <a-button
                        type="primary"
                        @click="$refs.editDialogRef.handleCreate()">
                        <template #icon>
                            <plus-outlined></plus-outlined>
                        </template>
                        添加成员
                    </a-button>
                    <template #extra>
                        <a-space>
                            <a-input v-model:value="searchFormData.keyword"></a-input>
                            <a-button
                                ghost
                                @click="search"
                                type="primary">
                                搜索
                            </a-button>
                        </a-space>
                    </template>
                </x-toolbar>
                <a-table
                    :columns="columns"
                    :data-source="listData"
                    :loading="loading"
                    :pagination="paginationState"
                    :scroll="{ x: 1000 }"
                    @change="onTableChange">
                    <template #bodyCell="{ column, record }">
                        <template v-if="'status' === column.key">
                            {{ record.status == 'ENABLED' ? '已启用' : '已禁用' }}
                        </template>
                        <template v-if="'action' === column.key">
                            <x-action-button @click="$refs.editDialogRef.handleEdit(record)">编辑</x-action-button>
                            <x-action-button
                                v-if="record.status == 'ENABLED'"
                                @click="handleRemove(record)"
                                >禁用</x-action-button
                            >
                            <x-action-button
                                v-else
                                @click="handleReStart(record)"
                                >启用</x-action-button
                            >
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>

    <edit-dialog
        :permissions="permissions"
        ref="editDialogRef"
        @ok="onOk"></edit-dialog>
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { onMounted, ref } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination } from '@/hooks'
import EditDialog from './components/EditDialog.vue'
import { useUserStore } from '@/store'
// import Role from './components/Role.vue'

defineOptions({
    name: 'systemRole',
})

const columns = [
    { title: '姓名', dataIndex: 'nickname', key: 'nickname', fixed: 'left', width: 160 },
    { title: '邮箱', dataIndex: 'email', width: 240 },
    { title: '手机号', dataIndex: 'mobile' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '操作', key: 'action', fixed: 'right', width: 120 },
]

const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } =
    usePagination()

const editDialogRef = ref()
const permissions = ref([])
const userStore = useUserStore()
console.log('userStore', userStore.userInfo)
/**
 * 获取用户列表
 * @returns {Promise<void>}
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { code, data } = await apis.system
            .getUserList({
                pageSize,
                pageNum: current,
                keyword: searchFormData.value.keyword,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === code) {
            const { records, pagination } = data
            listData.value = records
            paginationState.total = pagination.total
        }
    } catch (error) {
        hideLoading()
    }
}

const search = () => {
    getPageList()
}

/**
 * 禁用用户
 */
function handleRemove({ id }) {
    Modal.confirm({
        title: '禁用提示',
        content: '确认禁用？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
            return new Promise((resolve, reject) => {
                ;(async () => {
                    try {
                        const { code } = await apis.system.delUser(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === code) {
                            resolve()
                            message.success('禁用成功')
                            // const index = listData.value.findIndex((i) => i.id == id)
                            // const current = listData.value[index]
                            //  listData.value[index] = {...current,sts:'0'}
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}
/**
 * 启用用户
 */
function handleReStart({ id }) {
    Modal.confirm({
        title: '启用提示',
        content: '确认启用？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
            return new Promise((resolve, reject) => {
                ;(async () => {
                    try {
                        const { code } = await apis.system.reStartUser(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === code) {
                            resolve()
                            message.success('启用成功')
                            // const index = listData.value.findIndex((i) => i.id == id)
                            // const current = listData.value[index]
                            //  listData.value[index] = {...current,sts:'1'}
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}
/**
 * 分页
 */
function onTableChange({ current, pageSize }) {
    paginationState.current = current
    paginationState.pageSize = pageSize
    getPageList()
}

/**
 * 获取全部权限
 */
async function getPermission() {
    const result = await apis.user.getAuthList()
    const { code, data } = result || {}
    if (config('http.code.success') === code) {
        permissions.value = data.map((i) => ({ label: i.name, value: i.code, ...i }))
    }
}
/**
 * 编辑完成
 */
async function onOk() {
    await getPageList()
}

onMounted(() => {
    getPageList()
    getPermission()
})
</script>

<style lang="less" scoped></style>
